<template>
  <el-container class='elheight'>
    <el-aside class='appTree'>
      <app-tree :tree-data="treeData" v-on:appTreeClick="appTreeClick"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <div class="dzy-custom-search-box">
            <div>
              水域名称：<el-input placeholder="请输入名称" v-model="selectForm.waterName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              负责人姓名：<el-input placeholder="请输入姓名" v-model="selectForm.personInChargeName" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              负责人电话：<el-input placeholder="请输入电话" v-model="selectForm.personInChargePhone" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>
              水深：<el-input placeholder="请输入水深" v-model="selectForm.waterDepth" clearable class="dzy-custom-input"></el-input>
            </div>
            <div>水域类型：
              <el-select v-model="selectForm.waterType" placeholder="请选择" filterable clearable>
                  <el-option v-for="item in waterTypeOptions"
                    :key="item.id"
                    :value="item.code"
                    :label="item.name"></el-option>
                </el-select>
            </div>
            <div>
              危险等级：
              <el-select v-model="selectForm.dangerLevel" placeholder="请选择危险等级" filterable clearable>
                <el-option v-for="item in dangerLevelOptions"
                  :key="item.id"
                  :value="item.code"
                  :label="item.name"></el-option>
              </el-select>
            </div>
            <div>
              <el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button>
            </div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows">
          </app-table>
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" class="custom-dialog_style_twoLine" :before-close="cancel">
            <el-form :model="formData" label-width="50%" ref="formData" :rules="rules" :disabled="showOnly">
              <el-form-item label="水域编号：" label-width="30%">
                <el-input v-model="formData.waterNo" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="水域名称：" label-width="30%" prop='waterName'>
                <el-input v-model="formData.waterName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="水深（m）：" label-width="30%">
                <el-input v-model="formData.waterDepth" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="水域类型：" label-width="30%">
                <el-select v-model="formData.waterType" placeholder="请选择">
                  <el-option v-for="item in waterTypeOptions"
                                     :key="item.id"
                                     :value="item.code"
                                     :label="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="负责人：" label-width="30%" prop='personInChargeName'>
                <el-input v-model="formData.personInChargeName" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="联系方式：" label-width="30%" prop='personInChargePhone'>
                <el-input v-model="formData.personInChargePhone" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="水域负责人身份号：" label-width="30%" prop='personInChargeIdentity'>
                <el-input v-model="formData.personInChargeIdentity" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="危险等级：" label-width="30%">
                <el-select v-model="formData.dangerLevel" placeholder="请选择">
                  <el-option v-for="item in dangerLevelOptions"
                                     :key="item.id"
                                     :value="item.code"
                                     :label="item.name"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="面积（m²）：" label-width="30%" prop='waterArea'>
                <el-input v-model="formData.waterArea" autocomplete="off"></el-input>
              </el-form-item>
              <el-form-item label="是否有防范设施：" label-width="30%">
                <el-select v-model="formData.waterSignStatus" placeholder="请选择">
                  <el-option label="是" :value="1"></el-option>
                  <el-option label="否" :value="0"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="选择经纬度：" prop="longitude" class="custom-longla-container">
                <el-input v-model="formData.longitude" :disabled="true" placeholder="经度" ></el-input>
                <el-input v-model="formData.latitude" :disabled="true" placeholder="纬度" ></el-input>
                <el-button type="text" @click="openSimpleMap" style="color: red;">[ 选择 ]</el-button>
              </el-form-item>
              <el-form-item label="图片：" class="spcialLabel" style="width:100%;display:block">
                <app-upload ref="appUpload" v-model="formData.pictureArr" ></app-upload>
              </el-form-item>
              <el-form-item label="街道/社区/网格：" label-width="30%" prop="gridIdArr">
                <div class="block">
                  <el-cascader
                    placeholder="请选择"
                    :options="options"
                    filterable
                    :props="gridIdProps"
                    v-model="formData.gridIdArr">
                  </el-cascader>
                </div>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="save">确 定</el-button>
            </div>
          </el-dialog>
          <el-dialog class="dialog-body-mini" :visible.sync="showMap" title="选择经纬度" width="70%" top="8vh" :before-close="mapCancel">
        <edit-map v-if="showMap" :mode="mapMode" @appMapCallback="appMapCallback" :target="mapTarget" ></edit-map>
      </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import AppUpload from '@/components/AppMultiUpload'
import AppTree from '@/components/common/AppTree'
import AppTable from '@/components/AppTable'
import BtnGroup from '@/components/BtnGroup'
import EditMap from '@/components/EditMap'
import {getAllRegion} from '@/utils/region'
// import {createMapLocation} from '@/http/AppApi'
import {getUserGridTree} from '@/utils/SessionDataUtil'
import {validatePhone, validateIdefer} from '@/utils/validate'
import {findWater, createWater, updateWater, delWater} from '@/http/WaterApi'
import {getDictDataOption} from '@/utils/getDictDataOption'
export default {
  data () {
    return {
      dialogFormVisible: false,
      treeData: [],
      pageData: {},
      dialogTitle: '',
      currentSelectedData: [],
      showOnly: false,
      showMap: false,
      mapMode: 'simple',
      mapTarget: {},
      gridIdProps: {
        label: 'name',
        value: 'id'
      },
      tableColumns: [
        { prop: 'waterName', label: '水域名称' },
        { prop: 'waterArea', label: '面积（m²）' },
        { prop: 'personInChargeName', label: '负责人姓名' },
        { prop: 'personInChargePhone', label: '联系方式' },
        { prop: 'dangerLevel', label: '危险等级', formatter: this.filterType },
        { prop: 'waterSignStatus', label: '是否有防范设施', formatter: this.filterSign }
      ],
      options: [],
      waterTypeOptions: [],
      dangerLevelOptions: [],
      formData: {},
      selectForm: {},
      rules: {
        waterName: [
          { required: true, trigger: 'blur', message: '请输入水域名称' }
        ],
        waterArea: [
          { required: true, trigger: 'blur', message: '请输入水域面积' }
        ],
        personInChargeName: [
          { required: true, trigger: 'blur', message: '请输入负责人姓名' }
        ],
        personInChargePhone: [
          { required: true, validator: validatePhone, trigger: 'blur', message: '请输入负责人电话' }
        ],
        personInChargeIdentity: [
          { required: true, validator: validateIdefer, trigger: 'blur', message: '请输入负责人身份证' }
        ],
        longitude: [
          { required: true, message: '请选择经纬度', trigger: 'blur' }
        ],
        gridIdArr: [
          { required: true, message: '请选择网格', trigger: 'blur' }
        ]
      }
    }
  },
  components: {
    AppTree,
    BtnGroup,
    AppTable,
    AppUpload,
    EditMap
  },
  mounted () {
    this.getTreeData()
    this.getTableData()
    this.waterTypeOptions = getDictDataOption('水域类型')
    this.dangerLevelOptions = getDictDataOption('危险等级')
  },
  methods: {
    filterType (row, column) {
      let type = ''
      for (let i = 0; i < this.dangerLevelOptions.length; i++) {
        const element = this.dangerLevelOptions[i]
        if (row.dangerLevel === element.code) {
          type = element.name
          break
        }
      }
      return type
    },
    filterSign (row, column) {
      if (row.waterSignStatus === 0) {
        return '否'
      } else if (row.waterSignStatus === 1) {
        return '是'
      } else {
        return '未知'
      }
    },
    getTreeData () {
      let gridTree = getUserGridTree()
      if (gridTree && gridTree instanceof Array) {
        this.treeData = gridTree
        this.options = gridTree
      }
    },
    save () {
      if (this.isObjEmpty(this.formData)) return
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          let gridIdIndex = this.formData.gridIdArr.length - 1
          this.formData.gridId = this.formData.gridIdArr[gridIdIndex]
          this.formData.allGridId = this.formData.gridIdArr.join(',')
          if (this.formData.pictureArr) {
            this.formData.picture = this.formData.pictureArr.length === 0 ? '' : this.formData.pictureArr.join(',')
          }
          if (this.formData.id) {
            updateWater(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
                this.dialogFormVisible = false
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          } else {
            createWater(this.formData).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
                this.getTableData()
                this.dialogFormVisible = false
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          }
        }
      })
    },
    edit (row) {
      this.formData = row
      this.dialogTitle = '编辑部门信息'
      this.dialogFormVisible = true
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delWater(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.$message({
                  type: 'success',
                  message: '删除成功'
                })
                this.getTableData()
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
                return ''
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    cancel () {
      this.dialogFormVisible = false
      this.formData = {}
      this.$refs['formData'].resetFields()
      this.$refs.appUpload.clearFileList()
    },
    openSave () {
      this.dialogTitle = '添加部门信息'
      this.dialogFormVisible = true
    },
    getTableData (param) {
      findWater(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.pageData = resp.data
          if (this.pageData.items && this.pageData.items instanceof Array) {
            this.tableData = this.pageData.items
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
          return ''
        }
      })
    },
    handleCurrentChange (val) {
      this.selectForm.offset = (val - 1) * 10
      this.getTableData(this.selectForm)
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else {
        if (callbackData.btnType === 'post') {
          this.dialogTitle = '新增'
          if (this.formData.gridIdArr) {
            let arr = this.formData.gridIdArr
            this.formData = {}
            this.formData.gridIdArr = arr
          } else {
            this.formData = {}
          }
        } else {
          this.formData = JSON.parse(JSON.stringify(callbackData.rows[0]))
          let regionData = {}
          regionData.id = this.formData.gridId
          regionData.items = this.options
          this.$set(this.formData, 'gridIdArr', getAllRegion(regionData))
          this.formData.pictureArr = this.toArray(this.formData.picture)
        }
        this.showOnly = callbackData.sohwOnly
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    toArray (string) {
      let arr = []
      if (string) {
        let stringArr = string.split(',')
        for (let i = 0; i < stringArr.length; i++) {
          let obj = {}
          obj.name = 'IMG_' + i
          obj.url = stringArr[i]
          arr.push(obj)
        }
        return string.split(',')
      } else {
        return []
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else {
        this.currentSelectedData = []
      }
    },
    openSimpleMap () {
      this.mapMode = 'simple'
      this.showMap = true
      this.mapHackReset = true
    },
    appMapCallback (appMapInfo) {
      if (appMapInfo.lnglat) {
        this.formData.longitude = appMapInfo.lnglat.lng
        this.formData.latitude = appMapInfo.lnglat.lat
        this.showOnly = false
        this.showMap = false
      }
    },
    mapCancel () {
      this.mapHackReset = false
      this.showMap = false
    },
    appTreeClick (data) {
      let gridData = {}
      gridData.id = data.id
      gridData.items = this.options
      this.formData.gridIdArr = getAllRegion(gridData)
      this.getTableData({likeAllGridId: data.id})
    },
    searchHandleClick () {
      if (this.isObjEmpty(this.selectForm)) return
      this.getTableData(this.selectForm)
    },
    isObjEmpty (obj) {
      for (var key in obj) {
        return false
      }
      return true
    }
  }
}
</script>
<style scoped>
.custom-dialog_style_twoLine .el-form >>> .spcialLabel .el-form-item__label {
 width: 25%!important
}
</style>
